/*
 * @Author: 肖思汗 
 * @Date: 2025-09-05 15:17:56 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-09-05 21:57:55
 */


import { Button } from '@nutui/nutui-react-taro';
import { Image, Textarea } from "@tarojs/components";
import { ReactNode, useEffect, useRef, useState } from 'react';
import utilsApi from 'src/api/utilsApi';
import MyPopup from 'src/components/MyPopup/MyPopup';
import aiSVG from "./ai.svg";
import styles from './aiImage.module.less';
import aiImageStore from './aiImageStore';

import { observer } from "mobx-react-lite";
import utils from 'src/utils/utils';
import utilsStore from 'src/utils/utilsStore';
import designerRender from '../Designer/designerRender';


interface Iprops {
    children?: ReactNode
}

// ai生图按钮
const AiImage = observer((props: Iprops) => {

    const dom = useRef<HTMLDivElement | null>(null);
    const [data, setData] = useState({});
    const [prompt, setPrompt] = useState('');

    useEffect(() => {

    }, []);

    const handleConfirm = async () => {
        if (prompt.trim()) {
            try {
                const url = await utilsApi.aiImage(prompt);
                if (url) {
                    designerRender.addImg(url);
                    aiImageStore.setShow(false); // 使用store关闭弹窗
                }
                // setPrompt('');
            } catch (error) {
                console.error('AI生图失败:', error);
            }
        }
    };

    return (
        <>
            {/* 修改点击事件使用store控制弹窗 */}
            <div
                className={styles.aiImage}
                style={{
                    left: utils.rpx2px(40),
                    top: utilsStore.titleTop + utils.rpx2px(180) + utilsStore.windowWidth + utils.rpx2px(25),
                }}
                onClick={() => aiImageStore.toggleShow()}
            >
                <Image src={aiSVG} className={styles.icon} />
            </div>

            {/* 使用store的show状态控制弹窗显示 */}
            <MyPopup
                open={aiImageStore.show}
                onClose={() => aiImageStore.setShow(false)}
                title="AI生图"
                closeable
            // style={{ width: '100%', maxWidth: '500px' }}
            >
                <div style={{ padding: '20rpx' }}>
                    <Textarea
                        value={prompt}
                        onInput={(e) => setPrompt(e.detail.value)}
                        placeholder="请输入图片描述..."
                        className={styles.popupTextarea}
                    />
                    <Button
                        type="primary"
                        onClick={handleConfirm}
                        className={styles.popupConfirmBtn}
                    >
                        确认生成
                    </Button>
                </div>
            </MyPopup>
        </>
    );
});

export default AiImage;